import { useMemo, useState } from 'react';
import { Tabs, Button, Dropdown, Menu, Drawer, message, Modal } from 'antd';
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import { debounce } from 'lodash';
import { useApp } from '@inbiz/utils';
import SyncLang from './components/SyncLang';
import LangImportModal from './components/LangImportModal';
import { publishLang, getSyncLang } from './service';
import { getLangSiteType, getSiteType } from './utils';
import './style.less';
const { confirm } = Modal;
const { TabPane } = Tabs;

export default function Header(props: any) {
    const { currentSite, setCurrentSite, sites, allLangs, leftRef, queryRef, selectedRow } = props;
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [importVisible, setImportVisible] = useState(false);
    const [syncLoading, setSyncLoading] = useState(false);
    const [deleteData, setDeleteData] = useState<any[]>([]);
    const [modifyData, setModifyData] = useState<any[]>([]);
    const [closable, setClosable] = useState<boolean>(true);
    const appInfo: any = useApp();

    const isApp = useMemo(() => {
        return selectedRow?.OutId == appInfo?.OutId;
    }, [selectedRow, appInfo]);

    const showDrawer = () => {
        setDrawerVisible(true);
    };

    const onImport = () => {
        setImportVisible(true);
    };

    const onClose = () => {
        setDrawerVisible(false);
        queryRef?.current?.resetForm();
    };

    const onTabChange = (activeKey: string) => {
        queryRef?.current?.setData([]);
        queryRef?.current?.setTotal(0);
        queryRef?.current?.setSelectedRowKeys([]);
        const _site = sites?.find((item: { SiteType: string; }) => item?.SiteType == activeKey);
        leftRef?.current?.getTreeData(!_site, _site, (dataVersionId: string) => {
            const params = dataVersionId ? {
                isForm: true,
                queryLanguageType: '0',
                dataVersionId: dataVersionId,
            } : {
                siteOutId: _site?.OutId || '',
                dataVersionId: _site?.DataVersionId || '',
                queryLanguageType: 0,
                siteType: getLangSiteType(activeKey),
            }
            queryRef?.current?.getLangData(params);
        });
        leftRef?.current?.setSearchText('');
        queryRef?.current?.queryForm?.resetFields();
        queryRef?.current?.setCurrentType('0');
        setCurrentSite(activeKey);
    };

    const onPublish = async () => {
        confirm({
            content: '确认发布吗？',
            onOk: async () => {
                try {
                    const result = await publishLang(appInfo?.AppId);
                    if (result === true) {
                        message.success('发布成功');
                    }
                } catch (error: any) {
                    message.error(error)
                }
            },
        });
    };

    const onSyncUpdate = async () => {
        try {
            setSyncLoading(true);
            const results = await getSyncLang(appInfo?.App?.Id);
            if (results?.status == 204) {
                // 第一次同步
                message.success('同步更新成功');
                setSyncLoading(false);
                return;
            };
            const _deleteData = results?.RemovedItems?.length > 0 ? results?.RemovedItems?.map((item: { KindInfo: { KindCode: string; LangText: string; }[]; Key: string }) => {
                let langObject: any = {};
                item?.KindInfo?.map((item: { KindCode: string; LangText: string; }) => {
                    langObject[item?.KindCode] = item?.LangText
                });
                return {
                    Key: item?.Key,
                    op: true,
                    id: item?.Key,
                    ...langObject,
                };
            }) : [];
            const _modifyData = results?.ModifyItems?.length > 0 ? results?.ModifyItems?.map((item: any) => {
                return {
                    ...item,
                    id: item?.Key + item?.KindCode,
                    op: true,
                }
            }) : [];
            setModifyData(_modifyData);
            setDeleteData(_deleteData);
            setSyncLoading(false);
            showDrawer();
        } catch (error: any) {
            message.error(error);
            setSyncLoading(false);
        };
    };

    const onExport = () => {
        const appId = appInfo?.AppId || '';
        // const formData = queryRef?.current?.formQueryData || {};
        // let opt = JSON.parse(JSON.stringify(formData));
        // if (opt?.kindConditions) {
        //     opt.kindConditions = JSON.stringify(opt.kindConditions);
        // }
        const url = `/inbiz/api/services/languagengine/v3/language/export?appId=${appId}`;
        const iframe = document.createElement('iframe');
        iframe.src = decodeURI(url);
        iframe.style.display = 'none';
        try {
            document.body.appendChild(iframe);
        } catch (err) {
            console.log(err);
        }
        // 没有使用iframe.onload，有兼容问题，解决方案：轮询监听readyState;
        let timer = setInterval(() => {
            // @ts-ignore
            var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
            if (iframeDoc.readyState == 'complete' || iframeDoc.readyState == 'interactive') {
                if (iframeDoc.documentElement.innerText.indexOf('Error') > -1) {
                    message.error('服务器异常,请联系管理员处理。');
                } else {
                    message.success('导出成功');
                }
                document.body.removeChild(iframe);
                clearInterval(timer);
                return;
            };
        }, 2000);
    };

    const onLnagPreview = (e: any) => {
        const langCode = e?.key;
        const _site = sites?.find((item: { SiteType: string; }) => item?.SiteType == currentSite);
        const isDev = process.env.NODE_ENV === 'development';
        const origin = location.origin;
        let url = `${origin}/${isDev ? '' : `inbiz/${getSiteType(currentSite)}/`}${appInfo?.App?.Domain}${_site?.IsPublish ? `?lang=${langCode}` : `?v=${_site?.ReleaseVersionId}&lang=${langCode}`}#/${isDev ? 'preview/' : ''}${isApp ? appInfo?.DefaultPageRoute : `page/${selectedRow?.Name}`}`
        window.open(url);
    };

    const menu = useMemo(() => {
        return (
            <Menu onClick={onLnagPreview}>
                {
                    allLangs?.map((item: { Code: string; Name: string }) => {
                        return (
                            <Menu.Item key={item?.Code}>
                                {item?.Name}
                            </Menu.Item>
                        )
                    })
                }
            </Menu>
        );
    }, [allLangs, currentSite, isApp, selectedRow, sites]);

    const operations = useMemo(() => {
        return (
            <>
                <Button icon={<UploadOutlined />} onClick={onImport}>导入</Button>
                <Button icon={<DownloadOutlined />} onClick={debounce(() => onExport(), 500)}>导出</Button>
                <Button type='primary' onClick={onSyncUpdate} loading={syncLoading}>同步组件多语言</Button>
                <Dropdown overlay={menu}>
                    <Button>预览</Button>
                </Dropdown>
                <Button type='primary' onClick={onPublish}>发布</Button>
            </>
        )
    }, [menu, syncLoading]);

    const importCallback = () => {
        queryRef?.current?.opCallback();
    };

    return (
        <div className='inbiz-lang-manage-header'>
            <Tabs
                activeKey={currentSite}
                onChange={onTabChange}
                tabBarExtraContent={operations}
            >
                {
                    sites?.map((item: { key: string; label: string }) => {
                        return (
                            <TabPane key={item?.key} tab={item?.label} />
                        )
                    })
                }
            </Tabs>
            {
                drawerVisible
                &&
                <Drawer
                    title='同步组件多语言'
                    placement='right'
                    onClose={onClose}
                    visible={drawerVisible}
                    destroyOnClose={true}
                    width={800}
                    closable={closable}
                    maskClosable={false}
                    className='inbiz-lang-manage-drawer-wrapper'
                >
                    <SyncLang
                        leftRef={leftRef}
                        setClosable={setClosable}
                        sites={sites}
                        onClose={onClose}
                        allLangs={allLangs}
                        deleteData={deleteData}
                        setDeleteData={setDeleteData}
                        modifyData={modifyData}
                        setModifyData={setModifyData}
                    />
                </Drawer>
            }
            {
                importVisible && <LangImportModal visible={importVisible} setVisible={setImportVisible} callback={importCallback} />
            }
        </div>
    )
};